package pl.drypisy;

import java.util.ArrayList;
import java.util.Random;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

/** 
 * @author Marcin Pilat
 * @version 1.0
 * Activity which is invoked when user reach next point
 */
public class TaskActivity extends Activity {
	private TextView name;
	private TextView task;
	private TextView pointsTxt;
	private EditText answer;
	private Button okBut;
	private Button skipBut;
	private Button hintBut;
	private RadioGroup hintG;
	private ArrayList<RadioButton> hints = new ArrayList<RadioButton>();
	private Checkpoint cp;
	private int points;
	private DBAdapter base;
	
	/** Called when the activity is first created.	 */
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
		setContentView(R.layout.task);
		
		base = new DBAdapter(getBaseContext());
		//define gui elements
		name = (TextView)findViewById(R.id.cpName);
		task = (TextView)findViewById(R.id.cpTask);
		pointsTxt = (TextView)findViewById(R.id.cpPoints);
		answer = (EditText)findViewById(R.id.cpAnswer);
		okBut = (Button)findViewById(R.id.taskOkBtn);
		skipBut = (Button)findViewById(R.id.taskSkipBtn);
		hintBut = (Button)findViewById(R.id.taskHintBtn);
		
		hintG = (RadioGroup)findViewById(R.id.hintGroup);
		hintG.setVisibility(View.GONE);
		hintG.clearCheck();
		hints.add((RadioButton)findViewById(R.id.hint1));
		hints.add((RadioButton)findViewById(R.id.hint2));
		hints.add((RadioButton)findViewById(R.id.hint3));
		hints.add((RadioButton)findViewById(R.id.hint4));
		
		points = 4;
		
		skipBut.setOnClickListener(lisSkip);
		hintBut.setOnClickListener(lisHint);
		okBut.setOnClickListener(lisOK);
		
		Bundle extras = getIntent().getExtras();		
		
		if (extras != null){
			loadCheckpoint(extras.getInt("chid"));
		} else {
			Intent data = new Intent();
			data.setData(Uri.parse("Błąd"));
			setResult(RESULT_CANCELED, data);
			finish();
		}
	}
	
	
	/**
	 * @param chid Loaded checkpoint ID
	 * Load info about task, hint and answer and fill GUI elements
	 */
	private void loadCheckpoint(int chid){
		base.open();
		Cursor c = base.getCheckpoint(chid);
		base.close();
		if (c.moveToFirst()){
			cp = Checkpoint.getCheckpointFromCursor(c);
			name.setText(cp.getName());
			task.setText(cp.getTask());
			mixHints();
		}
	}
	
	/**
	 * Filling RadioButtons with mixed hints. 
	 */
	private void mixHints(){
		ArrayList<Integer> permutationTable = makePermutaion();
		for (RadioButton rb : hints){
			rb.setText(cp.getHints()[permutationTable.get(0)]);
			permutationTable.remove(0);
		}
	}
	
	private ArrayList<Integer> makePermutaion(){
		Random random = new Random();
		ArrayList<Integer> tmpA1 = new ArrayList<Integer>();
		ArrayList<Integer> tmpA2 = new ArrayList<Integer>();
		for (int k = 0 ; k < 4 ; ++k){
			tmpA1.add(k);
		}
		int tmp;
		for ( int i = 3 ; i > 0  ; --i){
			if (i != 0)
				tmp = (int)(random.nextDouble()*(i+1));
			else
				tmp = 0;
			tmpA2.add(tmpA1.get(tmp));
			tmpA1.remove(tmp);
		}
		tmpA2.add(tmpA1.get(0));
		tmpA1.remove(0);
		return tmpA2;
	}
	//Listener for skip Button. Show dialog, and end activity
    private OnClickListener lisSkip = new OnClickListener()
    {
		public void onClick(View v) {
			final AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
    	    builder.setMessage("Are you sure you want to skip this task?")
    	           .setCancelable(false)
    	           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
    	               public void onClick(DialogInterface dialog, int id) {
    	            	   points = 0;
    	       				Intent data = new Intent();
	    	       			data.setData(Uri.parse(""+points));
	    	       			setResult(RESULT_OK, data);
	    	       			finish();
    	               }
    	           })
    	           .setNegativeButton("No", new DialogInterface.OnClickListener() {
    	               public void onClick(DialogInterface dialog, int id) {
    	            	   dialog.cancel();
    	               }
    	           });
    	    final AlertDialog alert = builder.create();
    	    alert.show();
		}
	};
	
	//Listener for showHint Button
	private OnClickListener lisHint = new OnClickListener()
	    {
			public void onClick(View v) {
				hintG.setVisibility(View.VISIBLE);
				hintBut.setVisibility(View.GONE);
				answer.setVisibility(View.GONE);
				points = 2;
				Toast.makeText(getBaseContext(), "Możesz zdobyć tylko 2 punkty!", Toast.LENGTH_LONG).show();
				pointsTxt.setText("Zostay 2 punkty.");
			}
	};
	
	//Listener for OK button. Checking answer
	private OnClickListener lisOK = new OnClickListener()
    {
		public void onClick(View v) {
			String a = new String();
			
			if (hintG.isShown() && hintG.getCheckedRadioButtonId() != -1){
				a = ((RadioButton)findViewById(hintG.getCheckedRadioButtonId())).getText().toString().trim().toLowerCase();
			} else if (answer.isShown()){
				a = answer.getText().toString().trim().toLowerCase();
			}
			
			if (!(a.isEmpty())){
				if (checkAnswer(a)){
					Log.d("task","a poprawne");
					sendPoint();
				}else {
					--points;
					if (points != 1 && points != 0)
					Toast.makeText(getBaseContext(), "Zła odpowiedź.\nZostały " + points +" punkty.", Toast.LENGTH_LONG).show();
					if (points == 2){
						hintBut.setVisibility(View.GONE);
						hintG.setVisibility(View.VISIBLE);
						answer.setVisibility(View.GONE);
					}
					if(hintG.isShown()){
						if (points == 1){
							Log.d("1p", "1 punkt");							
							Toast.makeText(getBaseContext(), "Ostatni punkt, próbuj dalej...", Toast.LENGTH_LONG).show();
						} else if (points == 0) {
							sendPoint();
						}
					}
				}
			} else {
				Toast.makeText(getBaseContext(), "Podaj odpowiedź!", Toast.LENGTH_LONG).show();
			}
			if (points != 1)
				pointsTxt.setText("Zostały " + points + " punkty.");
			else
				pointsTxt.setText("Został 1 punkt.");
			a = "";
		}
	};
	
	//ending activity, and sendng point to map activity
	private void sendPoint(){
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage(getString(R.string.sendPoint))
	           .setCancelable(false)
	           .setPositiveButton(getString(R.string.taskOkBtn), new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   Intent data = new Intent();
	           			data.setData(Uri.parse(""+points));
	           			setResult(RESULT_OK, data);
	           			finish();
	               }
	           });
	    final AlertDialog alert = builder.create();
	    alert.show();
	}
	
	//Checking if s is answer
	private boolean checkAnswer(String s){
		if (cp.getAnswer().trim().toLowerCase().equals(s)){
			return true;
		} else {
			return false;
		}
	}
	
	/**
	 * Function from Activity. Block possibility of exit from activity without answer, or skip
	 */
	@Override
	public void onBackPressed(){
		final AlertDialog.Builder builder = new AlertDialog.Builder(this);
	    builder.setMessage(getString(R.string.skipTask))
	           .setCancelable(false)
	           .setPositiveButton(getString(R.string.btn_positive), new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   points = 0;
	       				Intent data = new Intent();
    	       			data.setData(Uri.parse(""+points));
    	       			setResult(RESULT_OK, data);
    	       			finish();
	               }
	           })
	           .setNegativeButton(getString(R.string.btn_negative), new DialogInterface.OnClickListener() {
	               public void onClick(DialogInterface dialog, int id) {
	            	   dialog.cancel();
	               }
	           });
	    final AlertDialog alert = builder.create();
	    alert.show();
	}
}
